package com.example.controller;

import com.example.common.Result;
import com.example.dto.LoginRequest;
import com.example.dto.RegisterRequest;
import com.example.dto.UserInfoResponse;
import com.example.service.UserService;
import com.example.util.JwtUtil;
import com.example.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            String result = userService.register(registerRequest);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.login(loginRequest);
            return Result.success("登录成功", token);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoResponse> getUserInfo() {
        try {
            // 从用户上下文中获取当前用户ID
            Long userId = UserContextUtil.requireCurrentUserId();
            UserInfoResponse userInfo = userService.getUserInfo(userId);
            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据用户ID获取用户信息（供其他服务调用）
     */
    @GetMapping("/{userId}/info")
    public Result<UserInfoResponse> getUserById(@PathVariable("userId") Long userId) {
        try {
            UserInfoResponse userInfo = userService.getUserInfo(userId);
            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量获取用户信息（供其他服务调用）
     */
    @PostMapping("/batch/info")
    public Result<Map<Long, UserInfoResponse>> getUsersByIds(@RequestBody List<Long> userIds) {
        try {
            Map<Long, UserInfoResponse> userInfoMap = userService.getUsersByIds(userIds);
            return Result.success(userInfoMap);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 验证token（供网关调用）
     */
    @PostMapping("/validate-token")
    public Result<UserInfoResponse> validateToken(@RequestParam("token") String token) {
        try {
            // 验证token
            if (!jwtUtil.validateToken(token)) {
                return Result.error(401, "token无效");
            }

            // 检查token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                return Result.error(401, "token已过期");
            }

            // 从token中获取用户信息
            Long userId = jwtUtil.getUserIdFromToken(token);
            String username = jwtUtil.getUsernameFromToken(token);
            
            if (userId == null || username == null) {
                return Result.error(401, "无法获取用户信息");
            }

            UserInfoResponse userInfo = new UserInfoResponse(userId, username);
            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error(401, "token验证失败");
        }
    }
}
